"""
    Copyright 2011 Kacper Żuk <kazuldur@gmail.com>

    This file is part of pyLastPlayer.

    pyLastPlayer is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    pyLastPlayer is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with pyLastPlayer.  If not, see <http://www.gnu.org/licenses/>.
"""
import os
import urllib.parse
import logging
from hashlib import md5
from PyQt4 import QtCore, QtGui
from SettingsUI import Ui_SettingsWindow
import LastLib

class Settings(QtGui.QDialog):
    def __init__(self, parent=None):
        QtGui.QDialog.__init__(self, parent)
        self.parent = parent
        self.ui = Ui_SettingsWindow()
        self.ui.setupUi(self)
        self.s = QtCore.QSettings()
        self.log = logging.getLogger("Settings")
        
        self.connect(self.ui.buttonLoginLibre, QtCore.SIGNAL("clicked()"), self.loginLibre)
        self.connect(self.ui.buttonLoginLast, QtCore.SIGNAL("clicked()"), self.loginLast)
        self.connect(self.ui.buttonLogoutLibre, QtCore.SIGNAL("clicked()"), self.logoutLibre)
        self.connect(self.ui.buttonLogoutLast, QtCore.SIGNAL("clicked()"), self.logoutLast)
        self.connect(self.ui.selectDirButton, QtCore.SIGNAL("clicked()"), self.selectDir)
        self.connect(self.ui.dirCheckBox, QtCore.SIGNAL("stateChanged(int)"), self.checkDir)
        self.connect(self.ui.downloadDir, QtCore.SIGNAL("editingFinished()"), self.checkDir)

        self.updateUI()

    def selectDir(self):
        dialog = QtGui.QFileDialog(self)
        dialog.setFileMode(QtGui.QFileDialog.Directory)
        dialog.setDirectory(os.path.expanduser("~"))
        dialog.setOption(QtGui.QFileDialog.ShowDirsOnly)
        if(dialog.exec()):
            self.ui.downloadDir.setText(dialog.selectedFiles()[0])

    def updateUI(self):
        if self.s.contains("settings/directory"):
            self.ui.downloadDir.setText(self.s.value("settings/directory"))
            self.ui.dirCheckBox.setCheckState(2)
        if self.s.value("settings/autosave") == "true":
            self.ui.autosaveCheckBox.setCheckState(2)
        else:
            self.ui.autosaveCheckBox.setCheckState(0)
        if self.s.value("settings/guessGenre") == "true":
            self.ui.guessGenre.setCheckState(2)
        else:
            self.ui.guessGenre.setCheckState(0)
        self.checkDir()

        if self.s.contains("services/service"):
            if int(self.s.value("services/service")) == 1:
                self.ui.radioButtonLibre.setChecked(True)
            elif int(self.s.value("services/service")) == 0:
                self.ui.radioButtonLast.setChecked(True)

        if self.s.contains("settings/scrobbleToAll"):
            self.ui.scrobbleToAll.setChecked(self.s.value("settings/scrobbleToAll") == "true")

        if self.s.contains("services/lastfm/user"):
            self.ui.labelLast.setText(self.s.value("services/lastfm/user"))
        else:
            self.ui.labelLast.setText("-")

        if self.s.contains("services/librefm/user"):
            self.ui.labelLibre.setText(self.s.value("services/librefm/user"))
        else:
            self.ui.labelLibre.setText("-")

    def logoutLibre(self):
        self.s.remove("services/librefm/user")
        self.s.remove("services/librefm/session")
        self.s.remove("services/librefm/password")
        self.updateUI()
        
    def logoutLast(self):
        self.s.remove("services/lastfm/user")
        self.s.remove("services/lastfm/session")
        self.updateUI()

    def login(self, s):
        l = LastLib.LastClient(s)
        token = l.getToken()
        e = token[0]
        if(e != 0):
            self.log.warning("Error in %s in login (%s): %s" % (LastLib.services[s][0], e, LastLib.errors[int(e)]))
            self._warning(self.tr("Service error"), self.tr("Error ("+e+"): ") + LastLib.errors[int(e)])
            return False
                
        params = {
                    "api_key": l.api_key,
                    "token": token[1],
                }
        url = LastLib.services[s][2]+urllib.parse.urlencode(params)
        if QtGui.QDesktopServices.openUrl(QtCore.QUrl(url)):
            QtGui.QMessageBox.information(self, self.tr("Notice"), self.tr("Please close this message AFTER you give pyLastPlayer permission to access your account."))
        else:
            QtGui.QMessageBox.information(self, self.tr("Notice"), self.tr("pyLastPlayer couldn't open your browser. Please open this url:") + url + self.tr("in your web browser and close this message AFTER you give pyLasyPlayer permission to access your account."))

        session = l.getSession(token[1])
        e = session[0]
        if(e != 0):
            self.log.warning("Error in %s in getSession (%s): %s" % (LastLib.services[s][0], e, LastLib.errors[int(e)]))
            self.showWarning(self.tr("Service error"), self.tr("Error ("+e+"): ") + LastLib.errors[int(e)])
            return False
        if s == 1:
            self.s.setValue("services/librefm/session", session[1])
            self.s.setValue("services/librefm/user", session[2])
            ## FIXME: needed by Libre.fm until they implement Scrobbling 2.0 API
            text, ok = QtGui.QInputDialog.getText(self, self.tr("Libre.fm password"),
                                          self.tr("Input your Libre.fm password\n(you won't get scrobbles otherwise):"), QtGui.QLineEdit.Password)
            if ok and text:
                self.s.setValue("services/librefm/password", md5(bytes(text, "utf8")).hexdigest())
        elif s == 0:
            self.s.setValue("services/lastfm/session", session[1])
            self.s.setValue("services/lastfm/user", session[2])
        self.updateUI()
        
    def loginLibre(self):
        self.ui.buttonLoginLibre.setEnabled(False)
        self.login(1)
        self.ui.buttonLoginLibre.setEnabled(True)

    def loginLast(self):
        self.ui.buttonLoginLast.setEnabled(False)
        self.login(0)
        self.ui.buttonLoginLast.setEnabled(True)

    def showWarning(self, title, text):
        QtGui.QMessageBox.warning(self, title, text)

    def checkDir(self, x = None):
        os.chdir(os.path.expanduser("~"))
        t = self.ui.downloadDir.text()
        if t:
            t = os.path.abspath(t)
            self.ui.downloadDir.setText(t)

        t = self.ui.dirCheckBox.isChecked()
        self.ui.downloadDir.setEnabled(t)
        self.ui.selectDirButton.setEnabled(t)
        self.ui.autosaveCheckBox.setEnabled(t)
        self.ui.guessGenre.setEnabled(t)
        
    def check(self):
        if self.ui.dirCheckBox.isChecked():
            t = self.ui.downloadDir.text()
            self.s.setValue("settings/directory", t)
            self.s.setValue("settings/autosave", self.ui.autosaveCheckBox.isChecked())
            self.s.setValue("settings/guessGenre", self.ui.guessGenre.isChecked())
        else:
            if self.s.contains("settings/directory"):
                self.s.remove("settings/directory")
        self.s.setValue("settings/scrobbleToAll", self.ui.scrobbleToAll.isChecked())
        if self.ui.radioButtonLast.isChecked():
            if not self.s.contains("services/lastfm/session"):
                self.showWarning(self.tr("Error"), self.tr("You need to log in to selected service"))
                return False
            else:
                self.s.setValue("services/service", 0)
                return True
        elif self.ui.radioButtonLibre.isChecked():
            if not self.s.contains("services/librefm/session"):
                self.showWarning(self.tr("Error"), self.tr("You need to log in to selected service"))
                return False
            else:
                self.s.setValue("services/service", 1)
                return True
        else:
            self.showWarning(self.tr("Error"), self.tr("You need to select a service"))
            return False

    def closeEvent(self, e):
        if not self.check():
            e.ignore()
        else:
            self.parent.settingsClosed()
        
    def accept(self):
        self.close()
